package com.wpre.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-12-15
 * Time: 15:50
 */
@Slf4j
@Configuration
public class RedisUtil {

    /**
     * RedisTemplate : 先将被存储的数据转换成 字节数组(不可读) ,再存储到Redis中,读取的时候按字节数组读取
     * StringRedisTemplate  : 直接存放的就是 String
     * 本项目存储的是< String,String>
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //设置值
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error,set{},{}", key, value);
            return false;
        }
    }

    //设置值

    /**
     * 可以设置过期时间
     *
     * @param key
     * @param value
     * @param time  单位: 秒
     * @return
     */
    public boolean set(String key, String value, Long time) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("RedisUtil error,set{},{},{}", key, value, time);
            return false;
        }
    }


    //获取值
    public String get(String key) {

        try {
            return StringUtils.hasText(key) ? stringRedisTemplate.opsForValue().get(key) : null;
        } catch (Exception e) {
            log.error("RedisUtil error,get{}", key);
            return null;
        }
    }

    public boolean del(String... key) {
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    //如果只有一个key
                    stringRedisTemplate.delete(key[0]);
                } else {
                    stringRedisTemplate.delete(
                            (Collection<String>) CollectionUtils.arrayToList(key)
                    );
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("del{}", e);
            return false;
        }
        return false;
    }

    //判断key是否存在

    public boolean hasKey(String key) {
        try {
            return StringUtils.hasText(key) ? stringRedisTemplate.hasKey(key) : false;
        } catch (Exception e) {
            log.error("RedisUtil hasKey{}", key);
            return false;
        }
    }


}
